<template>
  <el-form
    :model="userForm"
    :rules="userFormRules"
    ref="userForm"
    class="member-editor-inner"
    label-width="100px"
  >
    <el-row>
      <el-col :span="11">
        <el-row>
          <el-form-item label="姓名" prop="realname">
            <el-input v-model="userForm.realname" placeholder="姓名"></el-input>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="userForm.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item label="身份证号" prop="identityCard">
            <el-input
              v-model="userForm.identityCard"
              placeholder="身份证号"
              @blur="applyToBirthdayFromIdentityCode(userForm.identityCard)"
            />
          </el-form-item>
        </el-row>
      </el-col>

      <el-col :span="11" :offset="1">
        <el-form-item prop="headUrl" label="上传头像">
          <avatar-uploader
            :avatar="userForm.headUrl"
            title="我的头像"
            @uploaded="headerUploaded"
            :size="90"
          ></avatar-uploader>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="11">
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="userForm.mobile" placeholder="请输入11位手机号"></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="11" :offset="1">
        <el-form-item label="员工编号" prop="jobNumber">
          <el-input v-model="userForm.jobNumber" placeholder="员工编号"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="11">
        <el-form-item label="部门" prop="deptId">
          <el-cascader
            style="width:100%"
            filterable
            :options="deptTree"
            v-model="userForm.deptIds"
            :props="{
                label: 'name',
                value: 'id',
                checkStrictly: true
              }"
          >
            <template slot-scope="{node, data}">
              <span>{{ data.name }}</span>
            </template>
          </el-cascader>
        </el-form-item>
      </el-col>

      <el-col :span="11" :offset="1">
        <el-form-item label="生日" prop="birthdayStr">
          <el-date-picker
            style="width:100%"
            v-model="userForm.birthdayStr"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="生日"
          ></el-date-picker>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="11">
        <el-form-item label="学历" prop="education">
          <el-select style="width:100%" v-model="userForm.education" filterable placeholder="学历">
            <el-option
              v-for="item in formProperties.educationList"
              :key="item.id"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="11" :offset="1">
        <el-form-item label="籍贯" prop="nativePlace">
          <el-input v-model="userForm.nativePlace" placeholder="籍贯"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="11">
        <el-form-item label="职称" prop="professionalTitle">
          <el-select
            style="width:100%"
            filterable
            v-model="userForm.professionalTitle"
            placeholder="职称"
          >
            <el-option
              v-for="item in formProperties.professionalTitleList"
              :key="item.label"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="11" :offset="1">
        <el-form-item label="职务" prop="duty">
          <el-select style="width:100%" filterable v-model="userForm.duty" placeholder="职务">
            <el-option
              v-for="item in formProperties.dutyList"
              :key="item.id"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="11">
        <el-form-item label="工种类型" prop="craftList">
          <el-select
            style="width:100%"
            multiple
            filterable
            v-model="userForm.craftList"
            placeholder="点击选择工种"
          >
            <el-option
              v-for="item in formProperties.craftList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="11" :offset="1">
        <el-form-item label="政治面貌" prop="politicCountenance">
          <el-select
            style="width:100%"
            filterable
            v-model="userForm.politicCountenance"
            placeholder="政治面貌"
          >
            <el-option
              v-for="item in formProperties.politicCountenanceList"
              :key="item.id"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="11">
        <el-form-item label="入党时间" prop="joinThePartyTimeStr">
          <el-date-picker
            style="width:100%"
            v-model="userForm.joinThePartyTimeStr"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="入党时间"
          ></el-date-picker>
        </el-form-item>
      </el-col>

      <el-col v-show="!isEdit" :span="11" :offset="1">
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" placeholder="密码默认为身份证后6位" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row v-if="hasSaveButton">
      <el-col :span="11" :offset="12">
        <el-form-item style="marginTop:20px;textAlign:right;">
          <el-button type="primary" @click="save()">保存</el-button>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import AvatarUploader from '../../../components/uploader/avatar-uploader'
import { treeDataTranslate } from '@/utils'

export default {
  name: 'memberEditorInner',
  components: { AvatarUploader },
  props: {
    hasSaveButton: {
      type: Boolean,
      required: false,
      default: false
    }
  },
  data() {
    return {
      userForm: {
        userId: 0, // isEdit ? required : No
        headUrl: '',
        realname: '', // required 姓名
        gender: 1, // required 性别
        identityCard: '', // required 身份证号码
        deptId: null, // required 部门ID
        deptIds: [],
        birthdayStr: '', // 生日
        mobile: '', // 手机号码
        password: '', // 密码
        nativePlace: '', // 籍贯
        politicCountenance: '', // 政治面貌
        professionalTitle: '', // 职称
        duty: '', // 职务
        craftList: [], // 工种类型
        education: '', // 学历
        joinThePartyTimeStr: '', // 入党时间,
        jobNumber: '' // 员工编号
      },
      userFormRules: {
        realname: [
          {
            required: true,
            message: '真实姓名不能为空',
            trigger: 'blur'
          }
        ],
        deptId: [
          {
            required: true,
            message: '部门不能为空',
            trigger: 'blur'
          }
        ],
        gender: [
          {
            required: true,
            message: '性别不能为空',
            trigger: 'blur'
          }
        ],
        identityCard: [
          {
            required: true,
            message: '身份证号不能为空',
            trigger: 'blur'
          }
          // ,
          // {
          //   type: 'string',
          //   pattern: /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/,
          //   message: '请填写正确的身份证号码',
          //   trigger: 'blur'
          // }
        ],
        mobile: [
          {
            type: 'string',
            pattern: /^1(3|4|5|7|8)\d{9}$/,
            message: '请填写正确的手机号码',
            trigger: 'blur'
          }
        ]
      },
      isEdit: false
    }
  },
  methods: {
    async init(dept, userId) {
      // 初始化当前部门
      this.$refs.userForm.resetFields()

      this.$nextTick(async () => {
        if (userId) {
          this.isEdit = true
          await this.buildUserForm(userId)
          this.userForm.deptIds = this.getDeptTreeIds(this.userForm.deptId)
        } else {
          this.userForm.deptId = dept.id
          this.userForm.deptIds = this.getDeptTreeIds(dept.id)
        }
      })
    },
    getDeptTreeIds(deptId) {
      let dept = this.deptList.find(x => x.id === deptId)
      let ids = [dept.id]
      while (dept.parentId > 0) {
        let parentDept = this.deptList.find(x => x.id === dept.parentId)
        ids.splice(0, 0, parentDept.id)
        dept = parentDept
      }
      return ids
    },
    applyToBirthdayFromIdentityCode(code) {
      let regexp = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
      if (regexp.test(code)) {
        let [year, month, day] = [
          code.substr(6, 4),
          code.substr(10, 2),
          code.substr(12, 2)
        ]
        this.userForm.birthdayStr = `${year}-${month}-${day}`
      }
    },
    deptChanged(deptIdList) {
      this.userForm.deptId = deptIdList[deptIdList.length - 1]
    },
    headerUploaded(file) {
      this.userForm.headUrl = file.url
    },
    async buildUserForm(userId) {
      let res = await this.$http.post(`/usercenter-admin/user/info/${userId}`)
      let user = res.data
      this.userForm.userId = user.userId
      this.userForm.duty = user.duty
      this.userForm.gender = user.gender
      this.userForm.deptId = user.deptId
      this.userForm.mobile = user.mobile
      this.userForm.headUrl = user.headUrl
      this.userForm.realname = user.realname
      this.userForm.password = user.password
      this.userForm.craftList = user.craftList
      this.userForm.education = user.education
      this.userForm.birthdayStr = user.birthdayStr
      this.userForm.nativePlace = user.nativePlace
      this.userForm.identityCard = user.identityCard
      this.userForm.professionalTitle = user.professionalTitle
      this.userForm.politicCountenance = user.politicCountenance
      this.userForm.joinThePartyTimeStr = user.joinThePartyTimeStr
      this.userForm.jobNumber = user.jobNumber
    },
    buildRequest() {
      var request = JSON.parse(JSON.stringify(this.userForm))
      delete request.deptIds
      request.craftList = request.craftList ? request.craftList.join(',') : ''

      return request
    },
    async save() {
      let valid = await this.$refs.userForm.validate()
      if (!valid) return

      let request = this.buildRequest()
      let res = await this.$http({
        method: 'post',
        url: `/usercenter-admin/user/${this.isEdit ? 'update' : 'save'}`,
        data: request
      })
      if (res && res.code === 200) {
        this.$notify.success({ title: '成功', message: '保存用户信息成功' })
        this.$emit('saved')
        return true
      } else {
        this.$notify.error({ title: '错误', message: res.msg })
        return false
      }
    }
  },
  watch: {
    'userForm.deptIds'(newVal, oldVal) {
      if (newVal && newVal.length > 0) {
        this.userForm.deptId = newVal[newVal.length - 1]
      }
    }
  },
  computed: {
    formProperties() {
      return {
        professionalTitleList: this.$store.getters['user/professionalTitleList'],
        politicCountenanceList: this.$store.getters['user/politicCountenanceList'],
        educationList: this.$store.getters['user/educationList'],
        dutyList: this.$store.getters['user/dutyList'],
        craftList: this.$store.getters['user/craftList']
      }
    },
    deptList() {
      return this.$store.getters['user/deptList']
    },
    deptTree() {
      let deptList = this.$store.getters['user/deptList']
      // 防止state被更改
      let temp = JSON.parse(JSON.stringify(deptList))
      let tree = treeDataTranslate(temp, 'id')
      return tree
    }
  }
}
</script>

<style lang="less" scoped>
.member-editor-inner {
  .el-form-item {
    height: 32px;
  }
}
</style>
